package drawables;



import java.awt.Color;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorModel;

/**
 * 
 * @author David X. Wang
 *
 */
public class BrightnessContrastFilter implements BufferedImageOp {
	
	private int brightness;
	private double contrast;
	
	public void setBrightness(int brightness){
		this.brightness = brightness;
	}
	
	public void setContrast(int contrast){
		this.contrast = Math.pow(2, contrast/100d + 1) - 2;
	}

	@Override
	public BufferedImage filter(BufferedImage src, BufferedImage dest) {
		if(dest == null)
			dest = createCompatibleDestImage(src, null);
		int[] pixels = src.getRGB(0, 0, src.getWidth(), src.getHeight(), null, 0, src.getWidth());
		for(int i=0; i<pixels.length; i++){
			Color pixel = new Color(pixels[i]);
			pixels[i] = applyFilter(pixel).getRGB();
		}
		dest.setRGB(0, 0, src.getWidth(), src.getHeight(), pixels, 0, src.getWidth());
		return dest;
	}
	
	private Color applyFilter(Color pixel){
		if(brightness == 0 && contrast == 0)
			return pixel;
		Color newPix = new Color(filterValue(pixel.getRed()),
				filterValue(pixel.getGreen()),
				filterValue(pixel.getBlue()));
		return newPix;
	}
	
	private int filterValue(int value){
		value += brightness*255/100;
		value += (value-127)*contrast;
		value = Math.min(255, value);
		return Math.max(0, value);
	}

	@Override
	public Rectangle2D getBounds2D(BufferedImage src) {
		return new Rectangle(src.getWidth(), src.getHeight());
	}

	@Override
	public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
		return new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
	}

	@Override
	public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) {
		return null;
	}

	@Override
	public RenderingHints getRenderingHints() {
		return null;
	}

}
